package com.app.mingluxing.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.LoginResult;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.LogUtil;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 登录
 * Created by Administrator on 2015/7/20.
 */
public class LoginActivity extends BaseActivity {

    private TextView tv_forget_psw;
    private ImageView iv_delete_psw;
    private ImageView iv_delete_username;
    private EditText et_username;
    private EditText et_psw;
    private TextView tv_login;
    private Intent mIntent;
    //是否需要自动登录
    private boolean isAutoLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        isAutoLogin = getIntent().getBooleanExtra("isAutoLogin", true);

        mApplication.addActivity(this);

        initWidget();

        //自动登录
        autoLogin();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        et_username.setText(sp.getString(Constant.MOBILE, ""));
        et_psw.setText("");

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void initWidget() {

        et_psw = (EditText) findViewById(R.id.et_psw);
        et_username = (EditText) findViewById(R.id.et_username);
        iv_delete_psw = (ImageView) findViewById(R.id.iv_delete_psw);
        iv_delete_username = (ImageView) findViewById(R.id.iv_delete_username);
        tv_forget_psw = (TextView) findViewById(R.id.tv_forget_psw);
        tv_login = (TextView) findViewById(R.id.tv_login);
        TextView tv_register = (TextView) findViewById(R.id.tv_register);

        iv_delete_psw.setOnClickListener(this);
        iv_delete_username.setOnClickListener(this);
        tv_forget_psw.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        tv_register.setOnClickListener(this);

        et_username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //显示叉号
                    iv_delete_username.setVisibility(et_username.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);

                    et_username.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                            //显示叉号
                            iv_delete_username.setVisibility(et_username.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);

                        }

                        @Override
                        public void afterTextChanged(Editable editable) {
                        }
                    });

                } else {
                    iv_delete_username.setVisibility(View.INVISIBLE);

                }
            }
        });

        et_psw.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //显示叉号
                    iv_delete_psw.setVisibility(et_psw.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                    et_psw.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                            //显示叉号
                            iv_delete_psw.setVisibility(et_psw.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                        }

                        @Override
                        public void afterTextChanged(Editable editable) {

                        }
                    });

                } else {
                    iv_delete_psw.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    private void showSoftInput(EditText editText) {

        InputMethodManager inputManager =
                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_delete_psw:  //刪除密码

                et_psw.setText("");
                showSoftInput(et_psw);

                break;
            case R.id.iv_delete_username: //删除手机号

                et_username.setText("");
                showSoftInput(et_username);

                break;

            case R.id.tv_forget_psw://忘記密碼

                mIntent = new Intent(this, ForgetPswActivity.class);
                startActivity(mIntent);

                break;

            case R.id.tv_login:// 登錄

                if (CommonUtils.isNull(et_username.getText().toString().trim())) {
                    showToast("请输入用户名");
                    return;
                }

                if (!CommonUtils.isPhone(et_username.getText().toString().trim())) {
                    showToast("请输入正确的手机号码");
                    return;
                }

                if (CommonUtils.isNull(et_psw.getText().toString().trim())) {
                    showToast("请输入密码");
                    return;
                }

                String unEncryptpsw = et_psw.getText().toString().trim();
                //密码MD5加密
                String md5Psw = "";

                if (Constant.MINGLUXING_CODE.equals(unEncryptpsw)) {
                    //记住密码时 点击的登录
                    md5Psw = sp.getString(Constant.PSW, "");
                } else {
                    md5Psw = CommonUtils.toMd5(unEncryptpsw.getBytes());
                }

                login(et_username.getText().toString().trim(), md5Psw.toUpperCase());

                break;

            case R.id.tv_register:
                //注册
                mIntent = new Intent(this, RegisterActivity.class);
                startActivity(mIntent);

                break;

        }

    }

    private void login(final String userName, final String psw) {

        JSONObject j = new JSONObject();
        j.put("phoneNum", et_username.getText().toString().trim());
        j.put("pwd", psw);

        HttpUtil.setPostRequest("登录中...", this, Constant.WEB_ROOT + Constant.LOGIN,
               j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {

                        try {
                            LoginResult loginResult = JSONObject.parseObject(str, LoginResult.class);

//                    String get=sp.getString(Constant.LOGIN_PSW, "");
                            if (loginResult.code == Constant.STATUS_SUCCESS) {
                                if (loginResult.data == null || loginResult.token == null) {
                                    showToast("登陆失败");
                                    return;
                                }

                                //防止意外退出时 切换账号后 sp中文件未清理完全
                                if (!TextUtils.isEmpty(sp.getString(Constant.MOBILE, "")) && !userName.equals(sp.getString(Constant.MOBILE, ""))) {
                                    sp.edit().clear().apply();
                                }

                                //极光推送 设置推送的别名
                                if (loginResult.data.mobile != null)
                                    setAlias(loginResult.data.mobile);

                                //数据存储
                                SharedPreferences.Editor edit = sp.edit();
                                edit.putString(Constant.NAME, loginResult.data.name);
                                edit.putString(Constant.USERIMG, loginResult.data.userImg);
                                edit.putString(Constant.NICKNAME, loginResult.data.nickName);
                                edit.putString(Constant.TOKEN, loginResult.token.token);
                                edit.putString(Constant.AGE, loginResult.data.age);
                                edit.putString(Constant.PSW, loginResult.data.pwd);
                                edit.putString(Constant.SEX, loginResult.data.sex);
                                edit.putString(Constant.BIRTHDAY, loginResult.data.birthDay);
                                edit.putString(Constant.MOBILE, loginResult.data.mobile);
                                edit.putString(Constant.USERID, loginResult.data.mobile);
                                edit.putString(Constant.id, loginResult.data.id);
                                //记住用户名和密码
                                edit.putString(Constant.USERNAME, userName);
                                edit.putString(Constant.PSW, psw);

                                Object readObj = CommonUtils.readObj(Constant.REMAIND + userName);

                                if (readObj != null) {

                                    Set<String> remaind = (Set<String>) readObj;
                                    edit.putStringSet(Constant.REMAIND + userName, remaind).apply();

                                } else {
                                    Log.e("tag", " readObj 为 空 ");
                                }

                                edit.apply();

                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                startActivity(intent);
//                        finish();
                            } else {
                                //弹出错误提示
                                showToast(Constant.showErrorMsg(loginResult.code, LoginActivity.this));

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtil.e("TAG", str);
                        }

                    }
                }, null);
    }


    /**
     * 自动登录
     */
    private void autoLogin() {

        String userName = sp.getString(Constant.USERNAME, "");
        String psw = sp.getString(Constant.PSW, "");

        if (CommonUtils.isNull(userName) || CommonUtils.isNull(psw))
            return;

        et_username.setText(userName);
        et_psw.setText(Constant.MINGLUXING_CODE);

        et_username.setSelection(userName.length());
        et_psw.setSelection(Constant.MINGLUXING_CODE.length());

        //是否自动登录
        if (isAutoLogin)
            login(userName, psw);//记住的密码为md5加密后的 所以无需再MD5加密

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mApplication.exit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());
    }


    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    private void setAlias(String phone) {

        Log.e("tag", "设置tag : " + phone);

        if (CommonUtils.isNull(phone)) {
            LogUtil.e("TAG", "phone is empty");
            return;
        }
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, phone));
    }

    private static final int MSG_SET_ALIAS = 1002;

    private final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    LogUtil.e("TAG", "Set alias in handler. tag:" + ((String) msg.obj));
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    LogUtil.e("TAG", "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
//            String logs;
            switch (code) {
                case 0:

                    LogUtil.e("TAG", "设置别名成功");

                    break;
                case 6002:
//                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtil.e("TAG", " 设置tag 失败 ");
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
//                    logs = "Failed with errorCode = " + code;
                    LogUtil.e("TAG", "设置失败, 错误码:" + code);
            }

        }
    };

}
